<template>
    <el-dialog v-model="isOpen" title="计算结果" width="500" :border="true" align-center>
        <div class="eChartContainer flex-row justify-center align-center">
            <div ref="chartRef" class="pie_chart" />
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="isOpen = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { nextTick, ref, watch } from "vue"
import * as echarts             from "echarts"

let isOpen = defineModel()
let props  = defineProps([ "result" ])

const chartRef    = ref(null)
let chartInstance = null

watch(isOpen, (val) => {
    if(val){
        initChart()
    }
})

// 初始化图表
const initChart = () => {
    nextTick(() => {
        // 确保DOM已加载
        if(!chartRef.value){
            return
        }

        // 初始化图表实例
        if(!chartInstance){
            chartInstance = echarts.init(chartRef.value)
        }

        let details = props.result.details
        let pieData = details.map(item => {
            return {
                name : item.categoryName,
                value: item.value,
            }
        })

        // 配置图表选项
        const option = {
            tooltip: {
                trigger: "item",
            },
            legend : {
                left: "center",
            },
            series : [
                {
                    name             : "比例分布",
                    type             : "pie",
                    radius           : [ "40%", "70%" ],
                    avoidLabelOverlap: false,
                    itemStyle        : {
                        borderRadius: 10,
                        borderColor : "#fff",
                        borderWidth : 2,
                    },
                    label            : {
                        show      : false,
                        position  : "center",
                        formatter : "{d}%",
                        fontSize  : 18,
                        fontWeight: "bold",
                    },
                    emphasis         : {
                        label: {
                            show: true,
                        },
                    },
                    labelLine        : {
                        show: false,
                    },
                    data             : pieData,
                },
            ],
        }

        // 设置图表选项
        chartInstance.setOption(option)
    })
}

</script>

<style scoped>
.eChartContainer {
    height: 400px;

    .pie_chart {
        width: 100%;
        height: 100%;
    }
}
</style>
